package algorithm.alternateprinting;

import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.LockSupport;

/**
 * @auther zhouliangliang
 * @date 2022/10/8 14:36
 * @description
 * 使用 Semaphore
 */
public class AlternatePrintingTwo {
    private Semaphore semaphore1 = new Semaphore(0);
    private Semaphore semaphore2 = new Semaphore(0);


    Thread thread1 = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                for(int i=0; i<=10; i++) {
                    System.out.println(i);
                    semaphore2.release();
                    semaphore1.acquire();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    Thread thread2 = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                for(int i = 'A'; i<='J'; i++) {
                    semaphore2.acquire();
                    System.out.println((char) i);
                    semaphore1.release();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    private void run() {
        thread1.start();
        thread2.start();
    }

    public static void main(String[] args) {
        new AlternatePrintingTwo().run();
    }
}
